//
//  LZRestaurantSearchCityView.m
//  LzzizDemo
//
//  Created by xbnzd on 16/11/2.
//  Copyright © 2016年 xbnzd. All rights reserved.
//

#import "LZRestaurantSearchCityView.h"
#import "UIView+Rotation.h"
#import "LZSearchCityCell.h"
#import "IQKeyboardManager.h"
#import "CityManager.h"
#import "ProvinceModel.h"
#import "CitysModel.h"
#import "Masonry.h"
#import "LZMapLocationManager.h"
#import "LZSearchCityHeaderView.h"
#import "LZAlertView.h"

static NSString *searchCell = @"cell";

@interface LZRestaurantSearchCityView()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIView      *headBgView;
@property (nonatomic, strong) UILabel     *countryLabel;
@property (nonatomic, strong) UILabel     *cityLabel;
@property (nonatomic, strong) UIImageView *arrowImg;
@property (nonatomic, strong) UIImageView *positionImg;
@property (nonatomic, strong) UIButton    *positionBtn;
@property (nonatomic, strong) UIView      *headerGrayView;
@property (nonatomic, strong) NSArray     *dataArr;
@property (nonatomic, strong) NSArray     *searchRemandDataArr;
@property (nonatomic, assign) BOOL        isSearchRemand;//标记是否是搜索联想状态

@end

@implementation LZRestaurantSearchCityView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        [self initUI];
    }
    
    return self;
}

#pragma mark -
#pragma mark public action

- (void)showView {
    if (_isSearchRemand) {
        _isSearchRemand = NO;
        [self.tableView reloadData];
    }
    [self.tableView setContentOffset:CGPointMake(0, 0)];
}

- (void)showSearchRemandListWithSearchKey:(NSString *)key
{
    if (key.length > 0) {
        _isSearchRemand = YES;
        _searchRemandDataArr = [CityManager searchRemindwithKey:key];
    }else{
        _isSearchRemand = NO;
    }
    
    
    
    [self.tableView reloadData];
}

#pragma mark -
#pragma mark private action
- (void)positionBtnAction
{
    
    if ([LZMapLocationManager shareLocationManager].isOpenLocation) {
        // 如果开启了定位
        [[LZMapLocationManager shareLocationManager] startLocationSuccess:^(CLLocation *aLocation, NSString *cityName) {
            CitysModel *model = [CityManager searchTheModelWithKeyWord:cityName];
            [CityManager shareManager].currentShowCityModel =  model;
            
            [CitysModel setCityMessageWithCityEntity:model];
            
        } Failed:^(NSError *error) {
            [CityManager shareManager].currentShowCityModel =  [CityManager returnDefaultCityWhenLocationFailed];
        }];
    }
    else {
        // 如果没开定位
        [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
        
        LZAlertView *alert = [[LZAlertView alloc] initWithContent:LZLocalizedString(@"iphone_permissions_address_remind", nil) andImage:nil cancelButtonTitle:LZLocalizedString(@"cancel", nil) otherButtonTitles:LZLocalizedString(@"iphone_permissions_go_setting", nil),nil];
        [alert show];
        
        alert.clickButtonIndexBlock = ^(NSInteger index) {
            if (index == 1) {
                [[UIApplication sharedApplication]openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
            }
        };
    }
}

- (void)clickCurrentCityAction
{
    CitysModel *m = [CityManager searchTheModelWithKeyWord:self.cityLabel.text];
    [CityManager shareManager].currentShowCityModel = m;
    
    [CitysModel setCityMessageWithCityEntity:m];
}


#pragma mark -
#pragma mark tableview delegate datasource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (_isSearchRemand) {
        return 1;
    }
    return self.dataArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (_isSearchRemand) {
        return self.searchRemandDataArr.count;
    }
    ProvinceModel *m = self.dataArr[section];
    return m.citysArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (_isSearchRemand) {
        return 0;
    }
    return 52;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (_isSearchRemand) {
        return 0.01;
    }
    if (section < self.dataArr.count-1) {
        return 10.0;
    }
    return 0.01;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 52;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    static NSString *headerViewId = @"cityHeaderViewIdentifier";
    LZSearchCityHeaderView *headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:headerViewId];
    if (!headerView) {
        headerView = [[LZSearchCityHeaderView alloc] initWithReuseIdentifier:headerViewId];
    }
    
    if (self.dataArr.count>section) {
        ProvinceModel *m = self.dataArr[section];
        [headerView setLabelText:m.name];
    }
    
    return headerView;
    
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
   
    static NSString *footerViewId = @"cityFooterViewIdentifier";
    UITableViewHeaderFooterView *footerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:footerViewId];
    if (!footerView) {
        footerView = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:footerViewId];
        
        UIView *grayView = [[UIView alloc] init];
        grayView.backgroundColor = UIColorFromRGB(0xeeeeee, 1);
        [footerView addSubview:grayView];
        
        [grayView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(footerView);
        }];
    }
    
    return footerView;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    LZSearchCityCell *cell = [tableView dequeueReusableCellWithIdentifier:searchCell];
    if (!cell) {
        cell = [[NSBundle mainBundle] loadNibNamed:@"LZSearchCityCell" owner:nil options:nil].firstObject;
        
//        cell.backgroundColor = [UIColor clearColor];
        
    }
    CitysModel *cityM;
    if (_isSearchRemand) {
        cityM = self.searchRemandDataArr[indexPath.row];
    }else{
        ProvinceModel *m = self.dataArr[indexPath.section];
        NSArray *citysArr = m.citysArr;
        cityM = citysArr[indexPath.row];
        cell.lineView.hidden = (indexPath.row == citysArr.count-1);
    }
    
    cell.contentLabel.text = cityM.name;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    CitysModel *cityM;
    if (_isSearchRemand) {
        cityM = self.searchRemandDataArr[indexPath.row];
    }else{
        ProvinceModel *m = self.dataArr[indexPath.section];
        NSArray *citysArr = m.citysArr;
        cityM = citysArr[indexPath.row];
    }

    //重置数据
    [CityManager shareManager].currentShowCityModel = cityM;
    _isSearchRemand = NO;
    [self.tableView reloadData];
    
    [CitysModel setCityMessageWithCityEntity:cityM];
}

- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset {
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
}

#pragma mark -
#pragma mark UI

- (void)initUI
{
    [CityManager returnDataArrForSearchRemind];
    _dataArr = [CityManager returnDataArrForTableView];
    self.backgroundColor = [UIColor clearColor];
    [self addSubview:self.tableView];
    self.tableView.tableHeaderView = self.headBgView;
    [self.headBgView addSubview:self.countryLabel];
    [self.headBgView addSubview:self.cityLabel];
    [self.headBgView addSubview:self.positionImg];
    [self.headBgView addSubview:self.arrowImg];
    [self.headBgView addSubview:self.positionBtn];
    [self.headBgView addSubview:self.headerGrayView];
    
    self.countryLabel.text = LZLocalizedString(@"bahrain", nil);
    self.cityLabel.text = LZLocalizedString(@"manama", nil);
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickCurrentCityAction)];
    self.cityLabel.userInteractionEnabled = YES;
    [self.cityLabel addGestureRecognizer:tap];
    
    [self setSubviewsAutolayout];
}

- (void) setSelectCityModel:(CitysModel *)selectCityModel {
    _selectCityModel = selectCityModel;
    self.cityLabel.text = selectCityModel.name;
}

- (void)setSubviewsAutolayout
{
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(0);
        make.trailing.mas_equalTo(0);
        make.top.mas_equalTo(0);
        make.bottom.mas_equalTo(0);
    }];

    [self.countryLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(10);
        make.centerY.equalTo(self.headBgView).offset(-5);
    }];
    
    [self.arrowImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.countryLabel.trailing).offset(10);
        make.centerY.equalTo(self.headBgView).offset(-5);
    }];
    
    [self.cityLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.arrowImg.trailing).offset(10);
        make.centerY.equalTo(self.headBgView).offset(-5);
    }];
    
    [self.positionImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.equalTo(-10);
        make.height.and.width.equalTo(17);
        make.centerY.equalTo(self.headBgView).offset(-5);
    }];
    
    [self.positionBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.and.trailing.equalTo(0);
        make.top.mas_equalTo(0);
        make.bottom.mas_equalTo(-10);
    }];
    
    [self.headerGrayView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.and.trailing.and.bottom.equalTo(0);
        make.height.equalTo(10);
    }];
    
}

#pragma mark -
#pragma mark 初始化

- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.sectionFooterHeight = 0;
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    
    return _tableView;
}

- (UIView *)headBgView
{
    if (!_headBgView) {
        _headBgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 52+10)];
        _headBgView.backgroundColor = [UIColor clearColor];
    }
    
    return _headBgView;
}

- (UILabel *)countryLabel
{
    if (!_countryLabel) {
        _countryLabel = [[UILabel alloc] init];
        _countryLabel.textColor = UIColorFromRGB(0x999999, 1);
        _countryLabel.font = [UIFont systemFontOfSize:15];
        _countryLabel.backgroundColor = [UIColor clearColor];
    }
    
    return _countryLabel;

}

- (UILabel *)cityLabel
{
    if (!_cityLabel) {
        _cityLabel = [[UILabel alloc] init];
        _cityLabel.textColor = UIColorFromRGB(0x333333, 1);
        _cityLabel.font = [UIFont systemFontOfSize:15];
        _cityLabel.backgroundColor = [UIColor clearColor];
    }
    
    return _cityLabel;
}

- (UIImageView *)arrowImg
{
    if (!_arrowImg) {
        _arrowImg = [[UIImageView alloc] init];
        _arrowImg.image = [UIImage imageNamed:@"city_top_arrow"];
        [_arrowImg setLanguageRotaion];
    }
    return _arrowImg;
}

- (UIImageView *)positionImg
{
    if (!_positionImg) {
        _positionImg = [[UIImageView alloc] init];
        _positionImg.image = [UIImage imageNamed:@"positionicon"];
    }
    
    return _positionImg;
}

- (UIButton *)positionBtn
{
    if (!_positionBtn) {
        _positionBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _positionBtn.backgroundColor = [UIColor clearColor];
        [_positionBtn addTarget:self action:@selector(positionBtnAction) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return _positionBtn;
}

- (UIView *)headerGrayView {
    if (!_headerGrayView) {
        _headerGrayView = [[UIView alloc] init];
        _headerGrayView.backgroundColor = UIColorFromRGB(0xeeeeee, 1);
    }
    return _headerGrayView;
}

@end
